package com.wuyan.web.base.helper.convert;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import javax.persistence.AttributeConverter;
import java.util.Map;

/**
 * AttributeConverter: 此接口用于转化实体属性的
 * 将实体类中的Map与数据库中的String互转
 */

@Slf4j
public class Map2StringConvert implements AttributeConverter<Map<?, ?>, String> {
    private static final ObjectMapper mapper = new ObjectMapper();

    @Override
    public String convertToDatabaseColumn(Map<?, ?> value) {
        try {
            if (null == value) {
                return null;
            }

            return mapper.writeValueAsString(value);
        } catch (Exception e) {
            log.error("实体属性转换到表字段, {}", e.getMessage(), e);
        }

        return null;
    }

    @Override
    public Map<?, ?> convertToEntityAttribute(String value) {
        try {
            if (value == null) {
                return null;
            }

            return mapper.readValue(value, Map.class);
        } catch (Exception e) {
            log.error("表字段转换到实体属性, {}", e.getMessage(), e);
        }

        return null;
    }
}
